//
//  BkAgeListViewController.m
//  TuDianEducation
//
//  Created by lixinkeji on 2021/1/12.
//  Copyright © 2021 zhangbenchao. All rights reserved.

#import "BkAgeListViewController.h"
#import "BkGoodsDetailViewController.h"
#import "LXMessageViewController.h"

#import "BkAgeCollectionViewCell.h"
#import "BkSliderTableViewCell.h"
#import "BkMovieSelectView.h"

#import "LXMarketGoodsListModel.h"
#import "BookAgeHeaderView.h"
#import "LXSaveUserInforTool.h"

@interface BkAgeListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>{
    CGFloat left;
    CGFloat space;
    
}
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,assign) NSInteger row;
@property (nonatomic,strong) UIImageView *bigImgView;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic,strong) BookAgeHeaderView *faceHeaderView;
@property (nonatomic,strong) BkMovieSelectView *selcetView;

@property (nonatomic,strong) UITextField *searchTextFiled;
@property (nonatomic,strong) UIImageView *searchImg;
@property (nonatomic,strong) NSMutableArray *sliderArray;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,assign) NSInteger selctIndex;
///一级数组
@property (nonatomic,strong) NSArray *classify1Array;
@property (nonatomic,strong) NSDictionary *current1Dic;
///二级数组
@property (nonatomic,strong) NSArray *classify2Array;
@property (nonatomic,strong) NSDictionary *current2Dic;
///排序 0综合 1销量高 2销量低 3价格高 4价格低
@property (nonatomic,strong) NSString *sort;

//@property (nonatomic,assign) NSInteger firstSecn;
@property (nonatomic,strong) UIButton *messageBtn;

@end

@implementation BkAgeListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.row = 2;
    self.selctIndex = 0;
    [self.view addSubview:self.faceHeaderView];
    [self.view addSubview:self.selcetView];
    [self.view addSubview:self.collectionView];
   
    //[self.collectionView.mj_header beginRefreshing];
    self.view.backgroundColor = kWhiteColor;
    [self.view addSubview:self.tableView];

    
    [self navigationConfig];
    if (!self.currentIndex) {
        [self getclassify1listRqust];
    }
    NSArray *array =self.classify1Array.count?self.classify1Array: [LXSaveUserInforTool sharedUserTool].classify1Array;
    self.faceHeaderView.classify1Array = array;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:self.messageBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

-(UIButton *)messageBtn{
    if (!_messageBtn) {
        _messageBtn = [TSWLTools allocButtonTitle:@"" font:systemFont(TSScaleW(0)) textColor:kWhiteColor image:[UIImage imageNamed:@"wuxiaoxi"] frame:CGRectMake(0, 0, TSScaleW(40), TSScaleW(40)) sel:@selector(messageAction:) taget:self];
    }
    return _messageBtn;
}
-(void)messageAction:(UIButton *)sender
{
    LXMessageViewController *vc = [[LXMessageViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark ----获取未读消息数量

-(void)requstUnreadCount{
    //getmessnum
    [NetWorkTools postConJSONWithUrl:@"getmessnum" parameters:@{} success:^(id responseObject) {
       
        NSString *datastr = responseObject[@"datastr"];
//        if ([result integerValue] == 0) {
//            self.classify1Array = dataList;
//        }else{
//            [MBProgressHUD showError:resultNote];
//        }
        UIView *v = [self.messageBtn viewWithTag:22000000];
        if (v) {
            [v removeFromSuperview];
        }
        if (datastr.intValue !=0) {
           
            UILabel *unreadLabel = [TSWLTools allocLabel:datastr font:systemFont(TSScaleW(8)) textColor:kWhiteColor frame:CGRectMake(TSScaleW(30), TSScaleW(5), TSScaleW(18), TSScaleW(12)) textAlignment:(NSTextAlignmentCenter)];
            unreadLabel.tag = 22000000;
            [self.messageBtn addSubview:unreadLabel];
            unreadLabel.backgroundColor = kRedColor;
            unreadLabel.cornerRadius = unreadLabel.height/2.f;
           
            CGFloat w = [datastr boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, TSScaleW(10)) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:systemFont(TSScaleW(8))} context:nil].size.width;
            unreadLabel.width = w + TSScaleW(8);
            unreadLabel.left = self.messageBtn.width - unreadLabel.width;
        }
    } fail:^(NSError *error) {
        
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self requstUnreadCount];
}
-(void)navigationConfig{
    self.navigationItem.titleView = self.searchTextFiled;
    [self addRightNavgationItemWithImage:[UIImage imageNamed:@"wuxiaoxi"]];
//    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, TSScaleW(28), TSScaleW(28))];
//    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, TSScaleW(28), TSScaleW(28))];
//    imageView.image = [UIImage imageNamed:@"logo"];
//    [view addSubview:imageView];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:view];
//    self.navigationItem.leftBarButtonItem = leftItem;
}
-(BookAgeHeaderView *)faceHeaderView{
    if (!_faceHeaderView) {
        _faceHeaderView = [[BookAgeHeaderView alloc]init];
        WS(weakSelf);
        _faceHeaderView.selctIndex = _currentIndex?:0;
        _faceHeaderView.selctItemBlock = ^(NSInteger index) {
            NSArray *array =weakSelf.classify1Array.count?weakSelf.classify1Array: [LXSaveUserInforTool sharedUserTool].classify1Array;
//            if (array.count) {
//                for (int i = 0; i < array.count; i ++) {
//                    NSDictionary *dic = array[i];
//                    NSString *fid = weakSelf.firstDic[@"fid"];
//                    if ([fid isEqualToString:dic[@"fid"]]) {
//                        index = i;
//                    }
//                }
            
                weakSelf.current1Dic = array[index];
           // }
        };
    }
    return _faceHeaderView;
}
-(BkMovieSelectView *)selcetView{
    if (!_selcetView) {
        _selcetView = [[BkMovieSelectView alloc]init];
        _selcetView.top = _faceHeaderView.bottom;
        WS(weakSelf);
        _selcetView.btnBlock = ^{
            if (weakSelf.current2Dic) {
                [weakSelf.collectionView.mj_header beginRefreshing];
            }
        };
    }
    return _selcetView;
}

#pragma mark --消息事件
-(void)rigthBtnAction:(id)sender{
    LXMessageViewController *vc = [[LXMessageViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
-(UITextField *)searchTextFiled{
    if (!_searchTextFiled) {
        _searchTextFiled = [TSWLTools allocTextFieldTextFont:TSScaleW(14) placeHolderFont:TSScaleW(14) text:nil placeText:@"请输入商品名称进行搜索" textColor:kMainTxtColor placeHolderTextColor:kGrayTxtColor frame:CGRectMake(TSScaleW(12), TSScaleW(10),TSScaleW(260), TSScaleW(27))];
        _searchTextFiled.cornerRadius = _searchTextFiled.height/2.f;
        _searchTextFiled.leftViewMode = UITextFieldViewModeAlways;
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, TSScaleW(34), _searchTextFiled.height)];
        [view addSubview:self.searchImg];
        _searchTextFiled.leftView = view;
        _searchTextFiled.backgroundColor = kMainBgColor;
        _searchTextFiled.delegate = self;
    }
    return _searchTextFiled;
}
-(UIImageView *)searchImg{
    if (!_searchImg) {
        _searchImg = [[UIImageView alloc ]initWithFrame:CGRectMake(TSScaleW(15), TSScaleW(9), TSScaleW(12), TSScaleW(12))];
        _searchImg.image = [[UIImage imageNamed:@"搜索"] imageChangeColor:kMainTxtColor];
        _searchImg.centerY = _searchTextFiled.height/2.f;
    }
    return _searchImg;
}

-(UICollectionView *)collectionView
{
    if (!_collectionView) {
        
           left = TSScaleW(7);
           space = TSScaleW(7);
           _row = _row?:4;
           UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
           layout.itemSize = CGSizeMake((TSScaleW(273) - left * 2 - space * (_row - 1))/_row - 1,TSScaleW(166));
           layout.minimumLineSpacing = space;
           layout.minimumInteritemSpacing = space;
           layout.scrollDirection = UICollectionViewScrollDirectionVertical;
           
           
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(TSScaleW(102), _selcetView.bottom, TSScaleW(273), TSScreenHeight - Height_NavBar-_selcetView.bottom) collectionViewLayout:layout];
           _collectionView.delegate = self;
           _collectionView.dataSource = self;
           [_collectionView registerClass:[BkAgeCollectionViewCell class] forCellWithReuseIdentifier:@"BkAgeCollectionViewCell"];
        _collectionView.contentInset = UIEdgeInsetsMake(0, left, 0, left);
           _collectionView.scrollEnabled = YES;
           self.collectionView.backgroundColor = kWhiteColor;
        //手势添加
        //此处给其增加长按手势，用此手势触发cell移动效果
        [self.view addSubview:_collectionView];
       // [_collectionView addSubview:self.bigImgView];
        WS(weakSelf);
                     _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                             [weakSelf headerRefresh];
                     }];
                     _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                             [weakSelf footerRefresh];
                     }];
    }
    return _collectionView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    BkGoodsDetailViewController *vc = [[BkGoodsDetailViewController alloc]init];
    NSDictionary *dic = self.dataArray[indexPath.row];
    vc.gid = dic[@"gid"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        
    BkAgeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BkAgeCollectionViewCell" forIndexPath:indexPath];
    NSDictionary *dic = self.dataArray[indexPath.row];
    cell.dataDic =dic;
    WS(weakSelf);
    cell.addCarBlock = ^{
        [weakSelf getaddgoodscarWithGid:dic[@"gid"]];
    };
    return cell;
}
#pragma mark ----添加购物车

-(void)getaddgoodscarWithGid:(NSString *)gid
{
    ///默认一个
    if (![self ifNoLoginGotoLoginAction]) {
        return;
    }
    NSDictionary * pamas = @{@"gid":gid,@"numbers":@"1"};
    [NetWorkTools postConJSONWithUrl:@"addgoodscar" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
       
        if (result.integerValue == 0) {
            
        }else{
            
        }
        [MBProgressHUD showError:resultNote];
    } fail:^(NSError *error) {
        
    }];
}

/** 图片滚动回调 */
-(void)collectListReq
{
    NSDictionary * pamas = @{@"nowPage":[NSString stringWithFormat:@"%ld",self.pageNum],@"pageCount":[NSString stringWithFormat:@"%d",kPage_Size],@"content":_searchWords?:self.searchTextFiled.text,@"sort":[self sort],@"sid":self.current2Dic[@"sid"]};
    [NetWorkTools postConJSONWithUrl:@"getclassify2goodslist" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSArray *array = responseObject[@"dataList"];
        if (result.integerValue == 0) {
            
            [self handleListWithModel:array];
        }else{
             [MBProgressHUD showError:resultNote];
        }
         
    } fail:^(NSError *error) {
        
    }];

}
#pragma mark - 上拉、下拉

-(void)headerRefresh
{
    self.pageNum = 1;
    [self collectListReq];
    
}

-(void)footerRefresh
{
    [self collectListReq];
}
-(void)endRefrash

{
   if (self.collectionView.mj_header.state == MJRefreshStateRefreshing) {
        [self.collectionView.mj_header endRefreshing];
    }
    
    if (self.collectionView.mj_footer.state == MJRefreshStateRefreshing) {
        [self.collectionView.mj_footer endRefreshing];
    }
}
-(void)handleListWithModel:(id )result
{
    [self endRefrash];

    NSArray *array = result;
    if (self.pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    [self.dataArray addObjectsFromArray:array];
    
   
    
     [SSKJ_NoDataView showNoData:self.dataArray.count toView:self.collectionView offY:TSScaleW(10) message:@"您还没有数据哦~" imge:[UIImage imageNamed:@"nolikesimg"]];
    
    self.pageNum++;
    
    
    [self.collectionView reloadData];
    
    if (array.count != kPage_Size) {
        self.collectionView.mj_footer.state = MJRefreshStateNoMoreData;
    }else{

        self.collectionView.mj_footer.state = MJRefreshStateIdle;
    }
}


-(NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


#pragma mark ---sliderTabelView

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(TSScaleW(0), _selcetView.bottom, TSScaleW(102), TSScreenHeight - Height_NavBar-_selcetView.bottom) style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       
        if (@available(iOS 11.0, *))
        {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
        }
        else
        {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
//        WS(weakSelf);
//        _tableView.mj_header = [CustomGifHeader headerWithRefreshingBlock:^{
//                [weakSelf headerRefresh];
//        }];
//        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//                [weakSelf footerRefresh];
//        }];
    }
    return _tableView;
}


#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.classify2Array.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BkSliderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BkSliderTableViewCell"];
    if (!cell) {
        cell = [[BkSliderTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"BkSliderTableViewCell"];
  
    }
    cell.isSelct = indexPath.row == _selctIndex;
    NSDictionary *dic = self.classify2Array[indexPath.row];
    cell.nameLabel.text =dic[@"name"];
   
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _selctIndex = indexPath.row;
    self.current2Dic = self.classify2Array[indexPath.row];
    [self.tableView reloadData];
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return TSScaleW(50);
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]initWithFrame:CGRectZero];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, TSScreenWidth, 0)];
    view.backgroundColor = kMainBgColor;
    return view;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return CGFLOAT_MIN;
}


#pragma mark ---一级分类请求
-(void)getclassify1listRqust{
    [NetWorkTools postConJSONWithUrl:@"getclassify1list" parameters:@{} success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSArray *dataList = responseObject[@"dataList"];
        if ([result integerValue] == 0) {
            self.classify1Array = dataList;
            self.current1Dic = self.classify1Array.firstObject;
        }else{
            [MBProgressHUD showError:resultNote];
        }
    } fail:^(NSError *error) {
        
    }];
}
-(void)setCurrent1Dic:(NSDictionary *)current1Dic{
    _current1Dic = current1Dic;
    _selctIndex = 0;
    [self getgetclassify2listRqustWith1Id:_current1Dic[@"fid"]];
}
-(void)setClassify1Array:(NSArray *)classify1Array{
    _classify1Array = classify1Array;
    [LXSaveUserInforTool sharedUserTool].classify1Array = _classify1Array;
    self.faceHeaderView.classify1Array = _classify1Array;
}
#pragma mark ----二级分类

-(void)getgetclassify2listRqustWith1Id:(NSString *)idString{
    [NetWorkTools postConJSONWithUrl:@"getclassify2list" parameters:@{@"fid":idString} success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSArray *dataList = responseObject[@"dataList"];
        if ([result integerValue] == 0) {
            self.classify2Array = dataList;
        }else{
            [MBProgressHUD showError:resultNote];
        }
    } fail:^(NSError *error) {
        
    }];
}
-(void)setClassify2Array:(NSArray *)classify2Array
{
    _classify2Array = classify2Array;
    [self.tableView reloadData];
    if (_classify2Array.count) {
        if (self.secendName.length) {
            NSInteger dex = 0;
            for (int i = 0; i < _classify2Array.count; i ++) {
                NSDictionary *dic = _classify2Array[i];
                if ([dic[@"sid"] isEqual:_secendName]) {
                    dex = i;
                    _selctIndex = dex;
                }
            }
            self.current2Dic = _classify2Array[dex];
            
        }else{
            self.current2Dic = _classify2Array.firstObject;
        }
        
    }else{
        [self.dataArray removeAllObjects];
        [self.collectionView reloadData];
    }
    
}
-(void)setCurrent2Dic:(NSDictionary *)current2Dic{
    _current2Dic = current2Dic;
    [self.collectionView.mj_header beginRefreshing];
    
}
-(NSString *)sort{

    if (_selcetView.currentIndex == 0) {
        return @"0";
    }else
    {
       
        if (_selcetView.currentIndex == 1) {
            if (_selcetView.saleBtn.selected) {
                return @"1";
            }else{
                return @"2";
            }
        }
        
        if (_selcetView.currentIndex == 2) {
            if (_selcetView.priceBtn.selected) {
                return @"3";
            }else{
                return @"4";
            }
        }
    }
    return @"0";
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//    NSString *contentString = [textField.text stringByReplacingCharactersInRange:range withString:string];
//    if (contentString==nil) {
//        contentString = @"";
//    }
   // self.searchTextFiled.text = contentString;
    
    NSString *contentString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    self.searchWords = contentString;
    [self.collectionView.mj_header beginRefreshing];
    
    
    return YES;
}

@end
